import './index.scss'

import classNames from 'classnames'
import { useEffect, useRef, useState } from 'react'
import { Form, Text, View } from '@tarojs/components'

import { useApply, withUser } from '@/hooks'
import { goToPage, message } from '@/utils'
import { LxfButton, LxfCard, LxfCheckboxGroup } from '@/components'
import api from '@/api'
import { IApplyInfo, IFormItem } from '@/models/apply'
import { form2Comp } from '../util'
import { LxfConfirmModal } from '@/components/lxf-confirm-model'
import { IFloatWrapperRef } from '@/components/lxf-float-wrapper'

const baseCls = 'signup-page';

const SignUp = () => {
    const signRef = useRef<IFloatWrapperRef>();
    const [apply] = useApply();

    const [agree, setAgree] = useState<boolean>(false);
    const [province, setProvince] = useState<string>();
    const [city, setCity] = useState<string>();
    const [formItemList, setFormItemList] = useState<IFormItem[]>();
    const [formValues, setFormValues] = useState<any>();

    const handleConfirm = async () => {
        const info = formValues;

        Object.entries(info).forEach(([key, val]) => {
            const reg = /^([a-zA-Z]*)\[([0-9]+)\]$/;
            const value = val && !isNaN(Number(val)) ? Number(val) : val;
            if (reg.test(key)) {
                const keys = key.match(reg) ?? [];
                if (info[keys[1]]) {
                    info[keys[1]][keys[2]] = value;
                } else {
                    info[keys[1]] = { [keys[2]]: value }
                }
                delete info[key];
            } else if (key === 'city' && Array.isArray(value)) {
                // info[key] = value.join(',')
                info[key] = [value[0], value[1].substring(0, value[1].length - 1)].join(',');
            } else if (key === 'university') {
                info[key] = value;
            } else {
                info[key] = value;
            }
        })
        const params = { ...info };
        console.log('params------', params)
        const res = await api.lxf.postVolunteerApplyStep1Answer(params);
        if (res.info === "ok") {
            goToPage('/pages/signup/step2/video/index')
        } else {
            message.error(res.info);
        }
    }

    const handleSignUp = (e: any) => {
        setFormValues(e.target.value);
        signRef.current?.open();
    }
    const handleBindMobile = async (e) => {
        await api.lxf.updateVolunteerInfo(e.detail)
    }

    const handleFormItemChange = (e: any, name: string) => {
        const value = e.target.value;
        setFormItemList((prev) => {
            const newList = prev?.map(item => {
                const show = item?.skip_rule?.show;
                if (show?.[name]) {
                    if (show[name] == value) {
                        return { ...item, show: true };
                    } else {
                        return { ...item, show: false };
                    }
                } else {
                    return item;
                }

            })
            return newList;
        })
    }

    useEffect(async () => {
        if (!apply.step1ApplyInfo) {
            await apply.getStep1ApplyInfo();
        }
        const { step1ApplyInfo = {} } = apply ?? {};
        const { form_item_list } = step1ApplyInfo as IApplyInfo;
        setFormItemList(form_item_list);
    }, [])

    return (
        <View className={baseCls}>
            <View className={`${baseCls}-wrapper`}>
                <View className={"lxf_h1_text"}>一、个人信息注册</View>
                <View className={`${baseCls}-info`}>
                    <View className={classNames('lxf_info_text')}>欢迎报名成为蓝信封通信大使，本轮信息会用于评定你能否成为通信大使的考核项之一，请认真完成个人信息的填写。</View>
                    <LxfCard title={'手机*'}>
                        <LxfButton title='获取手机号' openType={"getPhoneNumber"} onGetPhoneNumber={handleBindMobile} />
                    </LxfCard>
                    <Form onSubmit={handleSignUp} className={`${baseCls}-info`}>
                        {formItemList?.map((item) => {
                            if (!item) return null;
                            const { title, required, type, name, options: _options, show } = item;
                            const options = Array.isArray(_options) ?
                                _options.map(opt => ({ label: opt, value: opt }))
                                : typeof _options === "object" ?
                                    Object.entries(_options)?.map(([key, value]) => ({ label: value, value: key }))
                                    : []
                            const Comp = form2Comp(type);
                            if (show === false) return null;
                            return <LxfCard title={`${title}${required ? '*' : ''}`} >
                                {Comp ?
                                    <Comp
                                        mode={type}
                                        name={name}
                                        options={options}
                                        placeholder={`请输入${title}`}
                                        province={province}
                                        city={city}
                                        setCity={setCity}
                                        setProvince={setProvince}
                                        onChange={(e: any) => handleFormItemChange(e, name)}

                                    />
                                    : null}
                            </LxfCard>
                        })}
                        <LxfCheckboxGroup onChange={e => setAgree(e.target.value.includes('agree'))} options={[{
                            label: <>我已阅读同意并遵守<Text className='link_text' onClick={() => goToPage('')}>服务协议</Text> </>,
                            value: 'agree'
                        }]} />
                        <View className={`${baseCls}-submit-btn`}>
                            <LxfButton title='提交' formType='submit' disabled={!agree} />
                        </View>
                    </Form>
                </View>
            </View>
            <LxfConfirmModal ref={signRef} title={"确定提交注册信息？"} showCancelBtn showOkBtn okText={"提交"} onOk={handleConfirm} />
        </View>
    )
}
export default withUser({
    auto: true,
    inject: true
})(SignUp)
